package com.mall.shopping.services;

import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @description:
 * @author: 牛犇
 * @date 2021/12/13 16:18
 */
@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    RedissonClient client;
    @Autowired
    ItemMapper itemMapper;

    @Override
    public  List<CartProductDto> getCartListById(CartListByIdRequest request) {
        //返回参数
        CartListByIdResponse response = new CartListByIdResponse();
        //购物车商品集合
        List<CartProductDto> cartProductDtos = new ArrayList<>();
        //校验参数
        request.requestCheck();
        //创建 或获取对应的表
        RMap<Long, CartProductDto> map = client.getMap(String.valueOf(request.getUserId()));
        //将redis里的商品加入购物车商品集合当中
        for (Long productId : map.keySet()) {
            CartProductDto cartProductDto = map.get(productId);
            cartProductDtos.add(cartProductDto);
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        return cartProductDtos;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
//         校验参数
        try {
            request.requestCheck();
        }catch (Exception e){
            //TODO
            response.setCode(ShoppingRetCode.REQUEST_CHECK_FAILURE.getCode());
            response.setMsg(ShoppingRetCode.REQUEST_CHECK_FAILURE.getMessage());
            return response;
        }
        Example example = new Example(Item.class);
        //通过id来获取商品
        example.createCriteria().andEqualTo("id", request.getProductId());
        List<Item> items = itemMapper.selectByExample(example);
        if (items.size() != 1) {
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
            return response;
        }
        //转化成我们要的dto
        CartProductDto cartProductDto = CartItemConverter.item2Dto(items.get(0));
        cartProductDto.setProductNum(request.getProductNum().longValue());
        cartProductDto.setChecked("false");
        //创建 或获取对应的表
        RMap<Long, CartProductDto> map = client.getMap(String.valueOf(request.getUserId()));
        map.put(request.getProductId(), cartProductDto);

        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        //校验参数
        request.requestCheck();
        //创建 或获取对应的表
        RMap<Long, CartProductDto> map = client.getMap(String.valueOf(request.getUserId()));
        //获得商品id对应的商品
        CartProductDto cartProductDto = map.get(request.getProductId());
        //修改该商品的数量
        cartProductDto.setProductNum(request.getProductNum().longValue());
        //修改该商品被选中的情况
        String checked;
        if (request.getChecked()){
            checked ="true";
        }else {
            checked ="false";
        }
        cartProductDto.setChecked(checked);
        //修改redis表
        map.replace(request.getProductId(), cartProductDto);

        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        }
        //得到请求需要改的check
        String checked = request.getChecked();
        //
        RMap<Long, CartProductDto> map = client.getMap(String.valueOf(request.getUserId()));
        Set<Long> keys = map.keySet();
        for (Long key : keys) {
            //查看目前商品的check
            String nowCheck = map.get(key).getChecked();
            //如果不对劲，修改成请求中要求的参数
            if (!(nowCheck.equals(checked))) {
                CartProductDto cartProductDto = map.get(key);
                cartProductDto.setChecked(checked);
                map.put(key,cartProductDto);
            }
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        //校验参数
        try{request.requestCheck();}
        catch (Exception e){
            response.setCode(ShoppingRetCode.REQUEST_CHECK_FAILURE.getCode());
            response.setMsg(ShoppingRetCode.REQUEST_CHECK_FAILURE.getMessage());
            return response;
        }
        //创建 或获取对应的表
        RMap<Long, CartProductDto> map = client.getMap(String.valueOf(request.getUserId()));

        map.remove(request.getItemId());
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {


        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();

        try {
            request.requestCheck();
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        }
        Long userId = request.getUserId();
        Map<Long, CartProductDto> map = client.getMap(String.valueOf(userId));
        Set<Long> keys = map.keySet();

        for (Long key : keys) {
            if (map.get(key).getChecked().equals("true")) {
                map.remove(key);
            }
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }

}
